package com.cbgolf.oa.app;

/**
 * Created by lq on 2017/11/14.
 */

import android.content.Context;
import android.os.Environment;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author lhn
 * @Description 应用程序异常类：用于捕获异常和提示错误信息
 * @created 2016-5-21
 */
public class AppException extends Exception implements Thread.UncaughtExceptionHandler {

    private static final long serialVersionUID = 1L;

    /**
     * 系统默认的UncaughtException处理类
     */
    private Thread.UncaughtExceptionHandler mDefaultHandler;

    /**
     * 无参的构造函数
     */
    private AppException() {
        this.mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    }

    /**
     * 有参的构造函数
     */
    private AppException(Exception excp) {
        super(excp);
        this.saveErrorLog(excp);
    }

    /**
     * @param excp(异常日志)
     * @Description 保存异常日志
     */
    public void saveErrorLog(Exception excp) {
        //定义错误日志文件存储信息
        String errorlog = "errorlog.txt";
        //文件输出
        FileWriter fw = null;
        PrintWriter pw = null;
        try {
            String dir = (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                    || !Environment.isExternalStorageRemovable()) ?
                    (App.getContext().getExternalCacheDir().getPath())
                    : App.getContext().getCacheDir().getPath();

//            //实例化logFile
            File logFile = new File(dir + File.separator + errorlog);
            //判断是否已经存在
            if (!logFile.exists()) {
                logFile.createNewFile();
            } else {
                logFile.delete();
                logFile.createNewFile();
            }
            //实例化文件输出
            fw = new FileWriter(logFile, true);
            pw = new PrintWriter(fw);
            //在命令行打印异常信息在程序中出错的位置及原因
            excp.printStackTrace(pw);
            //释放资源
            pw.close();
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (pw != null) {
                pw.close();
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                }
            }

        }
        //结束此错误Activity
//        ActivityCollector.finishAll();
    }

    /**
     * @return AppException
     * @Description 获取APP异常崩溃处理对象
     */
    public static AppException getAppExceptionHandler() {
        return new AppException();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {

        //如果异常没有被处理
        if (!handleException(ex) && mDefaultHandler != null) {
            //进行异常捕获
            mDefaultHandler.uncaughtException(thread, ex);
        }

    }

    /**
     * @param ex(异常信息)
     * @return true:处理了该异常信息;否则返回false
     * @Description 自定义异常处理:收集错误信息&发送错误报告
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        // APP崩溃异常报告
//        final String crashReport = getCrashReport(
//                OneLeadPosApplication.getOneLeadPosApplication(), ex);
        final String crashReport = getCrashReport(
                App.getContext(), ex);

        // 错误信息存储到本地
        saveErrorLog((Exception) ex);

        // 显示异常信息&发送报告(上传到服务器)
//        new Thread() {
//            public void run() {
//                Looper.prepare();
//                UIHelper.sendAppCrashReport(context, crashReport);
//                Looper.loop();
//            }
//
//        }.start();
        return true;
    }

    /**
     * @param context(上下文), Throwable ex(异常信息)
     * @return String
     * @Description 获取APP崩溃异常报告
     */
    private String getCrashReport(Context context, Throwable ex) {

        StringBuffer exceptionStr = new StringBuffer();
        // android版本以及系统型号
        exceptionStr.append("Android: " + android.os.Build.VERSION.RELEASE
                + "(" + android.os.Build.MODEL + ")\n");
        // 异常信息
        exceptionStr.append("Exception: " + ex.getMessage() + "\n");
        //？
        StackTraceElement[] elements = ex.getStackTrace();
        for (int i = 0; i < elements.length; i++) {
            exceptionStr.append(elements[i].toString() + "\n");
        }
        // 返回组成的StringBuffer
        return exceptionStr.toString();
    }
}